package com.wizo.csb.generator;

import java.util.Vector;
import java.util.Random;

/**
 * Generates a distribution by choosing from a discrete set of values.
 * @author ywu70
 *
 */
public class DiscreteGenerator extends Generator{
	
	class Pair{
		public double _weight;
		public String _value;
		
		Pair(double weight, String value){
			_weight = weight;
			_value = value;
		}
	}
	
	Vector<Pair> _values;
	Random _random;
	String _lastValue;
	
	public DiscreteGenerator(){
		_values = new Vector<Pair>();
		_random = new Random();
		_lastValue = null;
	}
	
	public void addValue(double weight, String value){
		_values.add(new Pair(weight, value));
	}
	
	/**
	 * Return the previous String generated by the distribution.
	 * Called lastString() should not advance the distribution or have any side effects.
	 * If nextString() has not been called yet, lastString() should return something reasonable. 
	 */
	public String lastString(){
		if(_lastValue==null)
			_lastValue = nextString();
		return _lastValue;
	}
	
	/**
	 * Generate the next String in the distribution.
	 */
	public String nextString(){
		double sum = 0;
		
		for(Pair p:_values)
			sum += p._weight;
		
		double value = _random.nextDouble();
		
		for(Pair p:_values){
			if(value<p._weight/sum){
				_lastValue = p._value;
				return p._value;
			}
			value -= p._weight/sum;
		}
		
		//In case some tricky error occurs.
		System.out.println("Some Tricky Error Occurs!");
		System.exit(0);
		
		return null;
	}
}
